剑指 Offer 29. 顺时针打印矩阵

题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

示例 1:

1
2
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

示例 2:

1
2
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]

限制:

  • $0 <= matrix.length <= 100$
  • $0 <= matrix[i].length <= 100$

注意:本题与主站 54 题相同:https://leetcode-cn.com/problems/spiral-matrix/


算法

(模拟) $O(n * m)$

螺旋矩阵II 思路一样
使用两个数组定义上右下左四个方向以及方向变量,开始默认从右走,用一个二维 $bool$ 数组 $st$ 存储每个位置是否被访问过,如果当前位置没有越界且没有被访问过就将其加入到答案数组中,否则改变方向继续往前走,直到走完矩阵中的所有元素。

时间复杂度

$O(n * m)$

空间复杂度

$O(n^2)$

C++ 代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
if (matrix.empty() || matrix[0].empty()) return res;
int n = matrix.size(), m = matrix[0].size();
vector<vector<bool>> st(n, vector<bool>(m, false));
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
for (int x = 0, y = 0, t = 0, d = 1; t < n * m; t ++ ) {
res.push_back(matrix[x][y]);
st[x][y] = true;
int a = x + dx[d], b = y + dy[d];
if (a < 0 || a >= n || b < 0 || b >= m || st[a][b]) {
d = (d + 1) % 4;
a = x + dx[d], b = y + dy[d];
}
x = a, y = b;
}
return res;
}
};
Author: tonngw
Link: https://tonngw.com/2022/07/09/剑指 Offer/剑指 Offer 29. 顺时针打印矩阵/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.